// vue.config.js
/**
 * @type {import('@vue/cli-service').ProjectOptions}
 */
require('shelljs/global');
const path = require('path');
const fs = require('fs');
const express = require('express');
const webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

if (process.env.NODE_ENV == 'production') {
  fs.exists(path.resolve('dist/.svn'), (exist) => {
    if (exist) {
      cp('-R', path.resolve('dist/.svn'), path.resolve());
    }
  });
}
const createBackDir = (dir) => {
  let srcPath = path.resolve(dir, 'src');
  mkdir('-p', srcPath);
  let staticPath = path.resolve(dir, 'static');
  fs.exists(staticPath, (exist) => {
    if (!exist) {
      mkdir('-p', staticPath);
    }
    cp('-R', 'src/static/*', staticPath);
  });
  fs.exists(path.resolve('.svn'), (exist) => {
    if (exist) {
      cp('-R', '.svn', dir);
      rm('-rf', path.resolve('.svn'));
    }
  });
  cp('-R', 'src/*', srcPath);
  cp('-R', 'index.html', srcPath);
};
const Version = Date.now().toString(30).slice(8);
process.env.VUE_APP_VERSION = Version;
module.exports = {
  // 选项...
  publicPath: './',
  outputDir: 'dist', //
  assetsDir: './static', //资源路径
  productionSourceMap: process.env.NODE_ENV == 'production' ? false : true,
  filenameHashing: false,
  lintOnSave: false,
  pages: {
    index: {
      entry: 'src/main.js',
      template: 'index.html' // 模板来源
    }
  },
  chainWebpack: (config) => {
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|JPG|gif|svg)(\?.*)?$/)
      .use('url-loader')
      .loader('url-loader')
      .tap((options) => {
        options.fallback.options.name = './static/imgs/[name].[ext]'; //?v=' + Version; //去除图片hash
        options.limit = 1024; //这是字节(Byte)限制，1KB = 1024Byte ,当图片的大小小于 1KB ,则会被转为 base64格式，打包进js文件，大于1KB,则会被打包进 img 文件夹，供链接请求获取。
        return options;
      });
    /*.options({
            limit: 1024,
            //publicPath: './static/',
            fallback: {
                loader: "file-loader",
                options: {
                    name: "./static/imgs/[name].[ext]?v="+Version,
                },
            },
        });*/
  },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
      config.mode = 'production';
      config.plugins.push({
        apply: (compiler) => {
          createBackDir(config.output.path);
        }
      });
    } else {
      // 为开发环境修改配置...
      config.mode = 'development';
    }
    // config.plugins.forEach((val) => {
    //       if (val instanceof HtmlWebpackPlugin) {
    //           console.log(val)
    //           console.log(val.options.templateParameters.toString())
    //       }
    // })
    /************plugins******************/
    const plugins = config.plugins;
    plugins.push(
      new CompressionPlugin({
        test: /\.(js|css)(\?.*)?$/i, //需要压缩的文件正则
        threshold: 10240, //文件大小大于这个值时启用压缩
        deleteOriginalAssets: false //压缩后保留原文件
      })
    );
    Object.assign(config.optimization.splitChunks, {
      chunks: 'all',
      minSize: 30000, //依赖包超过300000bit将被单独打包
      minChunks: 1, // 模块的最小被引用次数
      maxInitialRequests: 5, // 默认
      cacheGroups: {
        /*outside: {
                    name: 'outside',
                    test: /components[\\\/]/,
                    priority: -2,
                    enforce:true,
                    reuseExistingChunk:true,
                    chunks: 'initial'
                },*/
        tools: {
          name: 'tools',
          test: /jquery|promise|underscore|fastclick|vue|weixin-js-sdk[\\\/]/,
          priority: -5,
          enforce: true,
          reuseExistingChunk: true,
          chunks: 'initial'
        },
        alicdn: {
          name: 'ali',
          test: /ali-oss[\\\/]/,
          priority: -8,
          enforce: true,
          reuseExistingChunk: true,
          chunks: 'initial'
        },
        vendors: {
          name: 'vendors',
          test: /[\\\/]node_modules[\\\/]/,
          priority: -10,
          chunks: 'initial'
        },
        common: {
          name: 'common',
          minChunks: 2,
          priority: -20,
          chunks: 'initial',
          reuseExistingChunk: true
        }
      }
    });
    const customChunks = Object.values(config.optimization.splitChunks.cacheGroups).map((val) => {
      return val.name;
    });
    config.plugins.forEach((val, index) => {
      if (val instanceof HtmlWebpackPlugin) {
        val.options.chunks = customChunks.concat(['index']);
        val.options.chunksSortMode = 'manual';
        val.options.filename = 'main.html';
      }
    });
    /************ aligns******************/
    Object.assign(config, {
      // 开发生产共同配置
      resolve: {
        //extensions: ['.css', '.js', '.vue'], //请求本地json
        alias: {
          '@': path.resolve(__dirname, './src'),
          '@s': path.resolve(__dirname, './src/static'),
          '@c': path.resolve(__dirname, './src/components'),
          static: path.resolve(__dirname, './src/static'),
          components: path.resolve(__dirname, './src/components'),
          service: path.resolve(__dirname, './src/service')
        } // 别名配置
      }
    });
    config.output.filename = 'static/js/[name].js?v=' + Version;
    config.output.chunkFilename = 'static/js/[name].js?v=' + Version; //这种是给打包后的chunk文件加版本号
    //
  },
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: {
      //一种方式，打包后的css 会带版本号，不改变文件名的。
      filename: 'static/css/[name].css?v=' + Version,
      chunkFilename: 'static/css/[name].css?v=' + Version
      //一种方式，每次打包后的css文件名会变更新。
      //filename: 'css/[name].[' + 0.1 + '].css',
      //chunkFilename:'css/[name].[' + Version + '].css'
    }
  },
  transpileDependencies: ['swiper', 'dom7', 'ssr-window'],
  devServer: {
    open: process.platform === 'darwin',
    host: '0.0.0.0', // 允许外部ip访问
    port: 8089, // 端口
    contentBase: path.resolve('src'),
    before(app, serve) {
      //app.use(express.static(path.posix.join(__dirname, './src')))
    },
    https: false, // 启用https
    overlay: {
      warnings: true,
      errors: true
    }, // 错误、警告在页面弹出
    proxy: {
      '/web': {
        target: 'https://h5.wufae.com/Pingan/womentest',
        changeOrigin: true // 允许websockets跨域
        // ws: true,
        // pathRewrite: {
        //     "^/api": "",
        // },
      }
    } // 代理转发配置，用于调试环境
  }
};
